package com.lzy.springbootredis.controller;

import com.lzy.springbootredis.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/v1/coupon")
public class CouponController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("add")
    public JsonData getCoupon(@RequestParam(value = "coupon_id",required = true) int couponId){
        String uuid = UUID.randomUUID().toString();
        String couponKey = "lock:coupon:key"+couponId;
        lock(uuid, couponKey);

        return JsonData.buildSuccess();
    }

    private void lock(String uuid, String couponKey) {
        String luaScript = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(couponKey, uuid, 20, TimeUnit.SECONDS);
        System.out.println(uuid+"加锁状态："+lock);
        if (lock) {
            //加锁成功
            try{
                //todo 业务处理
                TimeUnit.SECONDS.sleep(10);

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //释放锁
                Long result = stringRedisTemplate.execute(new DefaultRedisScript<>(luaScript, Long.class), Arrays.asList(couponKey), uuid);
                System.out.println("解锁状态"+result);
            }

        }else{
            //自旋操作
            try {
                System.out.println("加锁失败，睡眠5秒进行自旋");
                TimeUnit.MILLISECONDS.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //重新获取锁
            lock(uuid,couponKey);
        }
    }
}
